package com.wcgksoft.source.DataCi;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author 阿良
 * @version 1.0.0
 * @ClassName NettyServer.java
 * @Description TODO
 * @createTime 2020年05月03日 19:16:00
 */
@Service
public class NettyServerS implements Runnable {
  private int port;
  private Channel channel;
  private EventLoopGroup bossGroup;
  private EventLoopGroup workerGroup;
  private Thread nserver;
  //初始化Netty服务
  @Autowired
  NettyServerInitializer nettyServerInitializer;

//  @PostConstruct
  public void init() {
    nserver = new Thread(this);
    nserver.start();
  }

//   @PreDestroy
  public void destory() {
    System.out.println("destroy server resources");
    if (null == channel) {
      System.out.println("server channel is null");
    }
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
    channel.closeFuture().syncUninterruptibly();
    bossGroup = null;
    workerGroup = null;
    channel = null;
  }

  public int getPort() {
    return port;
  }

  public void setPort(int port) {
    this.port = port;
  }

  @Override
  public void run() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    System.out.println(Thread.currentThread().getName() + "(19999)----数据采集线程开始工作！");
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup);
      b.channel(NioServerSocketChannel.class);
      b.childHandler(nettyServerInitializer);
      // 服务器绑定端口监听
     // ChannelFuture f = b.bind(15527).sync();
      ChannelFuture f = b.bind(19999).sync();//开启需要监听 的端口 多开端口
      // 监听服务器关闭监听
      f.channel().closeFuture().sync();
      channel = f.channel();
      // 可以简写为
      /* b.bind(portNumber).sync().channel().closeFuture().sync(); */
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }

}
